import {
  ActionType,
  ModalForm,
  PageContainer,
  ProCard,
  ProColumns,
  ProForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProTable
} from "@ant-design/pro-components";
import React, {useRef, useState} from "react";
import {Button, Form} from "antd";
import {EditOutlined, PlusOutlined, SettingFilled} from "@ant-design/icons";
import MapContainer from "@/components/AMap/MapContainer";
import MapAutoComplete from "@/components/AMap/MapAutoComplete";
import {globalApi, globalLoadTableApi, globalLoadTableApiCode, handleGloblApi} from "@/services/admin-api/globalApi";
import {citySelect} from "@/pages/Worker/Management";
import {Access, useAccess} from "umi";

type Store = {
  storeId: number;
  storeName: string;
  storeAddress: string;
  storeAddressLat: number;
  storeAddressLng: number;
  shopkeeperUsId: number;
  shopkeeperUsNickName: string;
  storeManagerUsId: number;
  storeManagerUsNickName: string;
  cityPartnerUsId: number;
  cityPartnerUsNickName: string;
  douyinPoiId: string
  cityCode: string;
  cityName: string;
  shopkeeperRate: number;
  storeManagerRate: number;
  cityPartnerRate: number;
  delFlag: boolean;
  createTime: string;
  createUserId: number;
  createUserName: string;
  updateTime: string;
  updateUserId: number;
  updateUserName: string;
};

const userSelect = await globalApi('/store/userSelect', {})

export default () => {

  const access = useAccess()

  const [modalOpen, handleModalOpen] = useState(false);
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const mapRef = useRef<any>()

  const columns: ProColumns<Store>[] = [
    {title: '门店ID', dataIndex: 'storeId', valueType: 'digit'},
    {title: '门店名称', dataIndex: 'storeName', valueType: 'text'},
    {title: '门店地址', dataIndex: 'storeAddress', valueType: 'text'},
    {title: '城市编码', dataIndex: 'cityCode', valueType: 'text'},
    {title: '城市', dataIndex: 'cityName', valueType: 'text'},
    {title: '抖音门店ID', dataIndex: 'douyinPoiId', valueType: 'text'},
    {title: '店主', dataIndex: 'shopkeeperUsNickName', valueType: 'text'},
    // {title: '店主', dataIndex: 'shopkeeperUsId', valueType: 'text'},
    {
      title: '店主分成',
      dataIndex: 'shopkeeperRate',
      valueType: 'digit',
      render: (_, r) => r.shopkeeperRate ? r.shopkeeperRate + '%' : ''
    },
    {title: '店长', dataIndex: 'storeManagerUsNickName', valueType: 'text'},
    // {title: '店长', dataIndex: 'storeManagerUsId', valueType: 'text'},
    {
      title: '店长分成',
      dataIndex: 'storeManagerRate',
      valueType: 'digit',
      render: (_, r) => r.storeManagerRate ? r.storeManagerRate + '%' : ''
    },
    {title: '城市合伙人', dataIndex: 'cityPartnerUsNickName', valueType: 'text'},
    // {title: '城市合伙人', dataIndex: 'cityPartnerUsId', valueType: 'text'},
    {
      title: '城市合伙人分成',
      dataIndex: 'cityPartnerRate',
      valueType: 'digit',
      render: (_, r) => r.cityPartnerRate ? r.cityPartnerRate + '%' : ''
    },
    {title: '地址经度', dataIndex: 'storeAddressLat', valueType: 'digit', hideInSearch: true,},
    {title: '地址维度', dataIndex: 'storeAddressLng', valueType: 'digit', hideInSearch: true,},
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>,
      render: (_, record) => [
        <Access accessible={access.canAuth('store:edit')}>
          <Button
            key={'edit_' + record.storeId} size="small" icon={<EditOutlined/>} type="primary"
            onClick={async () => {
              handleModalOpen(true);
              form.setFieldsValue({
                ...record,
                shopkeeperUs: record.shopkeeperUsId ? {
                  label: record.shopkeeperUsNickName,
                  value: record.shopkeeperUsId
                } : null,
                storeManagerUs: record.storeManagerUsId ? {
                  label: record.storeManagerUsNickName,
                  value: record.storeManagerUsId
                } : null,
                cityPartnerUs: record.cityPartnerUsId ? {
                  label: record.cityPartnerUsNickName,
                  value: record.cityPartnerUsId
                } : null,
                city: {label: record.cityName, value: record.cityCode},
              });
            }}
          />
        </Access>
      ],
      valueType: 'option',
    },
  ];

  const loadStoreMarker = () => {
    const formData = form.getFieldsValue()
    if (formData.storeAddressLng && formData.storeAddressLat) {
      const AMap = mapRef.current?.AMapC()
      mapRef.current?.addMarker(new AMap.LngLat(formData.storeAddressLng, formData.storeAddressLat))
    }
  }

  let timer: any

  return <PageContainer header={{title: '', breadcrumb: {},}}>
    <ProTable<Store>
      columns={columns} actionRef={actionRef}
      search={{span: 4}}
      headerTitle={
        <Access accessible={access.canAuth('store:add')}>
          <Button
            key="primary" type="primary" icon={<PlusOutlined/>} onClick={() => {
            handleModalOpen(true)
          }}/>
        </Access>
      }
      request={async (param) => globalLoadTableApiCode('/store/table', 'store:list:search', access, param)}
      rowKey={(record) => record.storeId}
      columnsState={{
        defaultValue: {
          delFlag: {show: false},
          createUserId: {show: false},
          updateUserId: {show: false},
          storeAddressLat: {show: false},
          storeAddressLng: {show: false},
        }
      }}/>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="800px" open={modalOpen} onOpenChange={handleModalOpen} form={form}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/store/saveOrUpdate', value)
        if (success) {
          actionRef.current?.reload();
          return true
        }
      }}
    >
      <ProCard>
        <MapContainer ref={mapRef} init={loadStoreMarker}/>
      </ProCard>

      <ProFormDigit label="店铺ID" name="storeId" hidden/>

      <MapAutoComplete
        label="店铺地址" rules={[{required: true}]} name="storeAddress" mapRef={mapRef} latLnt={(latLng: any) => {
        form.setFieldsValue({storeAddressLat: latLng.lat, storeAddressLng: latLng.lng})
      }}/>

      <ProForm.Group>
        <ProFormText label="店铺名称" rules={[{required: true}]} name="storeName"/>

        <ProFormText name={"douyinPoiId"} label={"抖音门店ID"}/>
      </ProForm.Group>

      <ProFormDigit label="地址经度" rules={[{required: true}]} name="storeAddressLat" hidden/>
      <ProFormDigit label="地址维度" rules={[{required: true}]} name="storeAddressLng" hidden/>

      <ProForm.Group>
        <ProFormDigit name={"shopkeeperUsId"} hidden/>
        <ProFormText name={"shopkeeperUsNickName"} hidden/>
        <ProFormSelect
          fieldProps={{
            labelInValue: true, onSelect: (value) => {
              console.log('value = ', value)
              form.setFieldsValue({shopkeeperUsId: value.value, shopkeeperUsNickName: value.label})
            }
          }} label={"店主"} name={"shopkeeperUs"} showSearch
          options={userSelect.data}/>
        <ProFormDigit name={"storeManagerUsId"} hidden/>
        <ProFormText name={"storeManagerUsNickName"} hidden/>
        <ProFormSelect
          fieldProps={{
            labelInValue: true, onSelect: (value) => {
              console.log('value = ', value)
              form.setFieldsValue({storeManagerUsId: value.value, storeManagerUsNickName: value.label})
            }
          }} label={"店长"} name={"storeManagerUs"} showSearch
          options={userSelect.data}/>
        <ProFormDigit name={"cityPartnerUsId"} hidden/>
        <ProFormText name={"cityPartnerUsNickName"} hidden/>
        <ProFormSelect
          fieldProps={{
            labelInValue: true, onSelect: (value) => {
              console.log('value = ', value)
              form.setFieldsValue({cityPartnerUsId: value.value, cityPartnerUsNickName: value.label})
            }
          }} label={"城市合伙人"} name={"cityPartnerUs"} showSearch
          options={userSelect.data}/>
        <ProFormText name={"cityCode"} hidden/>
        <ProFormText name={"cityName"} hidden/>
        <ProFormSelect
          fieldProps={{
            labelInValue: true, onSelect: (value) => {
              console.log('value = ', value)
              form.setFieldsValue({cityCode: value.value, cityName: value.label})
            }
          }} label={"城市"} name={"city"} showSearch rules={[{required: true}]}
          options={citySelect.data}/>

      </ProForm.Group>

      <ProForm.Group>
        <ProFormDigit label={"店主分成"} name={"shopkeeperRate"} width={"xs"} addonAfter={"%"}/>
        <ProFormDigit label={"店长分成"} name={"storeManagerRate"} width={"xs"} addonAfter={"%"}/>
        <ProFormDigit label={"城市合伙人分成"} name={"cityPartnerRate"} width={"xs"} addonAfter={"%"}/>
      </ProForm.Group>

    </ModalForm>
  </PageContainer>
}
